// 导入axios
import axios from 'axios'
import { ElMessage } from 'element-plus'
// import router from './router'
const service = axios.create({
  // baseURL: process.env.NODE_ENV == 'development'?'/api':'http://1.12.65.143:8091/',
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 20 * 1000,
  headers: {
    'Content-Type': 'application/json'
  }
})
// 2.请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('accessToken')
    if (token) {
      config.headers.accessToken = token
    }
    return config
  },
  (error) => {
    console.log('request error: ', error)
    return Promise.reject(error)
  }
)

// 3.响应拦截器
service.interceptors.response.use(
  (res) => {
    if (res.data.code === 401) {
      ElMessage.error(res.data.msg)
      // router.replace('/login')
      return false
    }
    // if(res.data.code !== 200){
    //   console.log("reject: ", res.data);
    //   return Promise.reject(res.data)
    // }
    return Promise.resolve(res.data)
  },
  (error) => {
    console.log('response error: ', error)
    if(error.response?.data?.message){
      ElMessage.error(error.response.data.message)
    }
    return Promise.reject(error)
  }
)

// get请求的封装
export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'get',
      params: params
    })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

// post请求封装  默认json格式:'Content-Type':'application/json',如果是文件上传，可以修改headers为 headers: { 'Content-Type': 'multipart/form-data' }
export function post(url, params = {}, headers = { 'Content-Type': 'application/json' }) {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'post',
      data: params,
      headers: headers
    })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

export default {
  get,
  post
}
